<?php
	class AuthController extends Zend_Controller_Action
	{
		function init()
		{
			$this->initView();
			$this->view->baseUrl = $this->_request->getBaseUrl();
		}
		
		function indexAction()
		{
			$this->_redirect('/');
		}
		
		function loginAction()
		{
			if ($this->_request->isPost()) 
			{
				// collect the data from the user
				Zend_Loader::loadClass('Zend_Filter_StripTags');
				
				$f = new Zend_Filter_StripTags();
				$username = $f->filter($this->_request->getPost('username'));
				$password = sha1($f->filter($this->_request->getPost('password')));
				
				if (empty($username)) 
				{
					$this->view->message = 'Introduzca un nombre de usuario.';
				} 
				else 
				{
					// setup Zend_Auth adapter for a database table
					Zend_Loader::loadClass('Zend_Auth_Adapter_DbTable');
					
					$db = Zend_Registry::get('db');
					$authAdapter = new Zend_Auth_Adapter_DbTable($db);
					$authAdapter->setTableName('user_view');
					$authAdapter->setIdentityColumn('user');
					$authAdapter->setCredentialColumn('password');
					
					// Set the input credential values to authenticate against
					$authAdapter->setIdentity($username);
					$authAdapter->setCredential($password);
					
					// do the authentication
					$auth = Zend_Auth::getInstance();
					$result = $auth->authenticate($authAdapter);
					
					if ($result->isValid()) 
					{
						// success: store database row to auth's storage
						// system. (Not the password though!)
						$data = $authAdapter->getResultRowObject(null,'password');
						$auth->getStorage()->write($data);
						$this->_redirect('/');
					} 
					else 
					{
						// failure: clear database row from session
						$this->view->message = 'Acceso incorrecto.';
					}
				}
			}
		}
		
		function logoutAction()
		{
			Zend_Auth::getInstance()->clearIdentity();
			$this->_redirect('/');
		}
	}